/**
 * 
 */
package com.agilegroup.crm.ui;

import static com.agilegroup.crm.utils.CONSTANTS.ADD_CONTACT_GET;
import static com.agilegroup.crm.utils.CONSTANTS.ADD_CONTACT_POST;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import roboguice.inject.InjectView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.agilegroup.crm.AgileApplication;
import com.agilegroup.crm.R;
import com.agilegroup.crm.adapters.AutoCompleteAdapter;
import com.agilegroup.crm.model.BasicView;
import com.agilegroup.crm.model.Contact;
import com.agilegroup.crm.model.LeadDetails;
import com.agilegroup.crm.requests.GenericJsonRequest;
import com.agilegroup.crm.requests.PostContactJsonRequest;
import com.agilegroup.crm.ui.fragments.ConnectionDialogFragment;
import com.agilegroup.crm.utils.OnlineChecker;
import com.agilegroup.crm.utils.SessionManager;
import com.agilegroup.crm.utils.Validation;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;

/**
 * @author Hisham
 *
 */
public class NewContactActivity extends BaseActivity {
	
	@InjectView(R.id.lblContactOwner)
	TextView lblContactOwner;
	
	@InjectView(R.id.txtFirstName)
	EditText txtFirstName;
	
	@InjectView(R.id.txtLastName)
	EditText txtLastName;
	
	@InjectView(R.id.txtTitle)
	EditText txtTitle;
	
	@InjectView(R.id.txtPhone)
	EditText txtPhone;
	
	@InjectView(R.id.txtMobile)
	EditText txtMobile;
	
	@InjectView(R.id.txtEmail)
	EditText txtEmail;
	
	@InjectView(R.id.autocomplete)
	AutoCompleteTextView txtCompany;
	
	private BasicView basicView;
	
	private SessionManager sessionManager;
	private static final String JSON_CACHE_KEY = "new_contact_get_json";
	private AutoCompleteAdapter autoCompleteAdapter;
	
	@SuppressWarnings("static-access")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_contact);
		
		sessionManager = new SessionManager(getBaseContext());    
    	HashMap<String, String> user = sessionManager.getUserDetails();
    	final String empId = user.get(sessionManager.KEY_ID);
    	
    	AgileApplication.getInstance().spiceManager.execute(new GenericJsonRequest<LeadDetails>(LeadDetails.class, empId, 
    			ADD_CONTACT_GET),JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new LeadDetailsListJsonRequestListener());
    	
    	autoCompleteAdapter = new AutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line);
    	txtCompany.setAdapter(autoCompleteAdapter);
    	
    	txtCompany.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
            	BasicView  view2 = (BasicView)parent.getItemAtPosition(position);
            	setBasicView(view2);
        }});
	}

	private class LeadDetailsListJsonRequestListener implements RequestListener<LeadDetails>{

		@Override
		public void onRequestFailure(SpiceException arg0) {
			Toast.makeText(NewContactActivity.this, "Failure", Toast.LENGTH_SHORT).show();
			
		}

		@Override
		public void onRequestSuccess(final LeadDetails leadDetails) {
			lblContactOwner.setText(leadDetails.getOwnerName());
		}
	}
	@SuppressWarnings("static-access")
	public void addLead(View v){
		List<String> list = new ArrayList<String>();
		StringBuilder builder = new StringBuilder();
		Validation validation = new Validation(this);
		
		boolean isMobileNull = validation.isTextFieldNull(txtMobile,R.string.message_mobile_required);
		boolean isCompanyNull = validation.isTextFieldNull(txtCompany,R.string.message_contact_company_required);
		boolean isFirstNameNull = validation.isTextFieldNull(txtFirstName,R.string.message_first_name_requried);
		boolean isEmailValid=true;
		
		if(isCompanyNull==false||isFirstNameNull==false||isMobileNull==false){
			String email = txtEmail.getText().toString();
			if(isCompanyNull==false){
				list.add(getResources().getString(R.string.message_contact_company_required));
			}
			if(isFirstNameNull==false){
				list.add(getResources().getString(R.string.message_first_name_requried));
			}
			if(isMobileNull==false){
				list.add(getResources().getString(R.string.message_mobile_required));
			}
			if(email!=null&&!email.equalsIgnoreCase("")){
				    isEmailValid = validation.isEmailValid(txtEmail);
				   if(isEmailValid==false){
					   list.add(getResources().getString(R.string.message_email_pattern_error));
				   }
			}
			for(String i : list)
			{
			     builder.append(i + "\n");
			}
			Toast.makeText(this, builder, Toast.LENGTH_LONG).show();
		}
		else{
			List<String> errorList = new ArrayList<String>();
			StringBuilder errorBuilder = new StringBuilder();
			String fName = txtFirstName.getText().toString();
			String lName = txtLastName.getText().toString();
			//String company = txtCompany.getText().toString();
			String title = txtTitle.getText().toString();
			String phone = txtPhone.getText().toString();
			String mobile = txtMobile.getText().toString();
			String email = txtEmail.getText().toString();
			
    		//BasicView basicView = (BasicView)txtCompany.getAdapter().getItem(txtCompany.getListSelection());
    		
    		HashMap<String, String> user = sessionManager.getUserDetails();
        	String empId = user.get(sessionManager.KEY_ID);
        	Contact lead = new Contact();
			
			lead.setCreatorId(Integer.parseInt(empId));
		
		   if(fName!=null&&!fName.equalsIgnoreCase("")){
			   lead.setfName(fName);
		   }
		   if(lName!=null&&!lName.equalsIgnoreCase("")){
			   lead.setlName(lName);
		   }
		   txtCompany.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				
				
			}
		   });
		   Log.d("Selecte Account", getBasicView().toString());
		   if(getBasicView()!=null){
			   lead.setParentId(getBasicView().getId());
			   lead.setParentName(getBasicView().getName());
			   lead.setViewType(basicView.getType());
		   }
//		   if(company!=null&&!company.equalsIgnoreCase("")){
//			   lead.setCompanyName(company);
//		   }
		   if(title!=null&&!title.equalsIgnoreCase("")){
			   lead.setTitle(title);
		   }
		   if(phone!=null&&!phone.equalsIgnoreCase("")){
			   lead.setPhone(phone);
		   }
		   if(mobile!=null&&!mobile.equalsIgnoreCase("")){
			   lead.setMobile(mobile);
		   }
		   if(email!=null&&!email.equalsIgnoreCase("")){
			    isEmailValid = validation.isEmailValid(txtEmail);
			   if(isEmailValid==true){
				   lead.setEmail(email);
				//   sucess=true;
			   }
			   else{
				 //  sucess=false;
				   errorList.add(getResources().getString(R.string.message_email_pattern_error));
			   }  
		   }
		   lead.setIsDeleted(false);
		   lead.setDateCreated(new Date());
		   if(isEmailValid!=true){
			   for(String i : errorList)
				{
				   errorBuilder.append(i + "\n");
				}
			   Toast.makeText(this, errorBuilder, Toast.LENGTH_SHORT).show();
		   }
		   else{
			   OnlineChecker checker = new OnlineChecker(this);
			   if(checker.isOnline()==true){
				   postNewContact(lead); 
			   }
			   else{
				   SherlockDialogFragment dialogFragment = new ConnectionDialogFragment();
	  			   dialogFragment.show(getSupportFragmentManager(), "connectionDialog");
			   }			   
		   }
		}
	}
	
	public void postNewContact(Contact contact){
		AgileApplication.getInstance().spiceManager.execute(new PostContactJsonRequest(contact,ADD_CONTACT_POST), new newContactJsonRequestListener());
	}
	public class newContactJsonRequestListener implements RequestListener<Contact>{

		@Override
		public void onRequestFailure(SpiceException spiceException) {
			Toast.makeText(NewContactActivity.this, "Failure", Toast.LENGTH_SHORT).show();
			
		}

		@Override
		public void onRequestSuccess(Contact result) {
			Toast.makeText(NewContactActivity.this, "Sucess", Toast.LENGTH_SHORT).show();
			finish();
			
		}
		
	}
	public void cancelButton(View v){
		finish();
	}
	public BasicView getBasicView() {
		return basicView;
	}

	public void setBasicView(BasicView basicView) {
		this.basicView = basicView;
	}
}